package com.example.qt.ptplatform.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.qt.ptplatform.entity.Download;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.util.List;

@Mapper
public interface DownloadMapper extends BaseMapper<Download> {
    // 查询指定用户在指定时间范围内的下载量总和
    @Select("SELECT SUM(download_size) FROM downloads " +
            "WHERE user_id = #{userId} " +
            "AND download_time BETWEEN #{startTime} AND #{endTime}")
    Double getTotalDownloadSizeByUserIdAndTimeRange(
            @Param("userId") Integer userId,
            @Param("startTime") LocalDateTime startTime,
            @Param("endTime") LocalDateTime endTime);

    @Select("SELECT d.*, t.title AS torrentTitle " +
            "FROM downloads d " +
            "LEFT JOIN torrents t ON d.torrent_id = t.torrent_id " +
            "WHERE d.user_id = #{userId} " +
            "ORDER BY d.download_time DESC " +
            "LIMIT #{offset}, #{perPage}")
    List<Download> getDownloadRecordsWithTorrentTitle(@Param("userId") Integer userId,
                                                      @Param("offset") Integer offset,
                                                      @Param("perPage") Integer perPage);

    // 获取总记录数
    @Select("SELECT COUNT(*) FROM downloads d WHERE d.user_id = #{userId}")
    int countDownloadsByUserId(@Param("userId") Integer userId);

    /**
     * 统计用户在指定时间内的总下载量（单位：字节）
     * @param userId    用户ID
     * @param startTime 时间窗口起始时间
     */
    @Select("SELECT COALESCE(SUM(download_size), 0) " +
            "FROM downloads " +
            "WHERE user_id = #{userId} AND download_time >= #{startTime}")
    Float sumUserDownloadInPeriod(
            @Param("userId") Integer userId,
            @Param("startTime") ZonedDateTime startTime
    );
}
